package com.surfacing.rcp.client.view.admin;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;


import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.part.ViewPart;

import com.surfacing.rcp.client.controller.EditorNewDoctorAction;
import com.surfacing.rcp.client.controller.RefreshViewAction;
import com.surfacing.rcp.client.editors.DoctorEditor;
import com.surfacing.rcp.client.editors.DoctorEditorInput;
import com.surfacing.rcp.client.modelManager.ModelFactory;
import com.surfacing.rcp.client.modelManager.SessionManager;
import com.surfacing.rcp.client.providers.DoctorContentProvider;
import com.surfacing.rcp.client.providers.DoctorLabelProvider;
import com.surfacing.rcp.client.util.CustomColors;
import com.surfacing.rcp.model.entity.Doctor;

public class DoctorAdminView extends ViewPart implements PropertyChangeListener {
	private static final Logger log = Logger.getLogger(DoctorAdminView.class);
	public static final String ID = "com.surfacing.rcp.client.view.admin.docotrAdminView";

	// properties
	private TableViewer viewer;
	private FormToolkit toolkit;
	private ScrolledForm form;
	private String authorization = "Benutzer";

	/**
	 * Default class constructor
	 */
	public DoctorAdminView() {
		ModelFactory.getInstance().getDoctorManager()
				.addPropertyChangeListener(this);
		checkAuthorization();
	}

	private void checkAuthorization() {
		if (SessionManager.getInstance().getLoginInformation() != null) {
			authorization = SessionManager.getInstance().getLoginInformation()
					.getAuthorization();
		}

		if (!authorization.equalsIgnoreCase("Administrator")) {
			if (form != null) {
				form.setEnabled(false);
				form.getDisplay().beep();
				form.setMessage(
						"Funktion kann nur von einem Administrator durchgef�hrt werden",
						IMessageProvider.ERROR);
			}
		} else {
			if (form != null)
				form.setEnabled(true);
		}

		if (log.isDebugEnabled())
			log.debug("Doctor AdminView Request from Authorization: "
					+ ((authorization == null) ? "Auth: Null" : authorization));
	}

	/**
	 * Cleanup the view
	 */
	@Override
	public void dispose() {
		ModelFactory.getInstance().getDoctorManager()
				.removePropertyChangeListener(this);
	}

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	@Override
	public void createPartControl(final Composite parent) {
		// the scrolled form
		toolkit = new FormToolkit(CustomColors.FORM_COLOR(parent.getDisplay()));
		form = toolkit.createScrolledForm(parent);
		form.setText("Liste der Mitarbeiter");

		if (!authorization.equalsIgnoreCase("Administrator"))
			form.setEnabled(false);

		toolkit.decorateFormHeading(form.getForm());
		GridLayout layout = new GridLayout();
		layout.horizontalSpacing = 0;
		layout.verticalSpacing = 0;
		layout.marginHeight = 0;
		layout.marginWidth = 0;
		form.getBody().setLayout(layout);
		form.getBody().setLayoutData(new GridData(GridData.FILL_BOTH));

		viewer = new TableViewer(form.getBody(), SWT.SINGLE | SWT.BORDER
				| SWT.H_SCROLL | SWT.V_SCROLL);
		viewer.getTable().setLayout(new GridLayout());
		viewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			@Override
			public void doubleClick(DoubleClickEvent dce) {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection) selection)
						.getFirstElement();
				Doctor member = (Doctor) obj;
				// Login login = ModelFactory.getInstance().getLoggerinManager()
				// .getLoggerinByUsername(member.getUserName());
				// // assert valid
				// if (login == null) {
				// Activator
				// .getDefault()
				// .log("Failed to open the editor for the staff member "
				// + member
				// + "\n The login object for the user is null",
				// IStatus.ERROR);
				// MessageDialog.openError(getSite().getShell(),
				// "Fehler beim �ndern von " + member.getUserName(),
				// "Der Mitarbeiter" + member.getFirstName() + " "
				// + member.getLastName()
				// + " kann nicht editiert werden");
				// }

				DoctorEditorInput input = new DoctorEditorInput(member, false);
				IWorkbenchPage page = PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getActivePage();
				try {
					page.openEditor(input, DoctorEditor.ID);
				} catch (PartInitException e) {
					log.warn("Failed to open the editor for the staff member "
							+ member.toString());
				}
			}
		});
		viewer.setContentProvider(new DoctorContentProvider());
		viewer.setLabelProvider(new DoctorLabelProvider());
		viewer.setInput(ModelFactory.getInstance().getDoctorManager()
				.getStaffList());
		getViewSite().setSelectionProvider(viewer);

		// add actions to the toolbar
		createToolBarActions();

		// set this table as a selection provider
		getViewSite().setSelectionProvider(viewer);
	}

	/**
	 * Passes the focus to the view
	 */
	@Override
	public void setFocus() {
		form.setFocus();
		checkAuthorization();
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		String event = evt.getPropertyName();
		if ("DOCTOR_CLEARED".equalsIgnoreCase(event)
				|| "DOCTOR_UPDATE".equalsIgnoreCase(event)
				|| "DOCTOR_REMOVE".equalsIgnoreCase(event)
				|| "DOCTOR_ADD".equalsIgnoreCase(event)) {
			// just refresh the viewer
			viewer.refresh();
		}
	}

	/**
	 * Creates and adds the actions for the toolbar
	 */
	private void createToolBarActions() {
		// create the action
		EditorNewDoctorAction addAction = new EditorNewDoctorAction(PlatformUI
				.getWorkbench().getActiveWorkbenchWindow());
		RefreshViewAction refreshView = new RefreshViewAction(Doctor.ID);
		// add to the toolbar
		form.getToolBarManager().add(addAction);
		form.getToolBarManager().add(refreshView);
		form.getToolBarManager().update(true);
	}
}